﻿#include "udpunicast.h"

#include <QDebug>

namespace Common {

	UdpUnicast::UdpUnicast(QObject *parent)
		: QObject(parent)
		, m_pUdpSocket(new QUdpSocket(this))
		, m_bBind(false)
	{
		connect(m_pUdpSocket, SIGNAL(readyRead()), this, SLOT(slotUnicastReadyRead()));
		connect(m_pUdpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(slotSocketStateChange(QAbstractSocket::SocketState)));
	}

	UdpUnicast::~UdpUnicast()
	{
		if (m_pUdpSocket != NULL)
		{
			m_pUdpSocket->close();
			delete m_pUdpSocket;
			m_pUdpSocket = NULL;
		}
	}

	QUdpSocket *UdpUnicast::getUdpSocket()
	{
		return m_pUdpSocket;
	}

	bool UdpUnicast::createUnicast(QString ip, int port)
	{
		if (port <= 0 && port > USHRT_MAX || ip.isEmpty())
		{
			return false;
		}

		m_bBind = m_pUdpSocket->bind(QHostAddress(ip), port);
		return m_bBind;
	}

	bool UdpUnicast::createUnicast(int port)
	{
		if (port <= 0 && port > USHRT_MAX)
		{
			return false;
		}

		m_bBind = m_pUdpSocket->bind(port);
		return m_bBind;
	}

	bool UdpUnicast::closeUnicast()
	{
		m_pUdpSocket->abort();
		return true;
	}

	bool UdpUnicast::sendToUnicastMsg(QString targetIp, int targetPort, QByteArray buff)
	{
		if (!m_bBind)
		{
			return false;
		}

		m_pUdpSocket->writeDatagram(buff, QHostAddress(targetIp), targetPort);
		return true;
	}

	void UdpUnicast::slotUnicastReadyRead()
	{
		while (m_pUdpSocket->hasPendingDatagrams())
		{
			QByteArray buff;
			buff.resize(m_pUdpSocket->pendingDatagramSize());
			QHostAddress peerAddr;    // 数据来源Ip
			quint16 peerPort;         // 数据来源端口
			m_pUdpSocket->readDatagram(buff.data(), buff.size(), &peerAddr, &peerPort);

			emit signalRecvUnicastMsg(peerAddr.toString(), peerPort, buff);
		}
	}

	void UdpUnicast::slotSocketStateChange(QAbstractSocket::SocketState state)
	{
		switch (state) {
		case QAbstractSocket::UnconnectedState:
		{

			break;
		}
		case QAbstractSocket::HostLookupState:
		{

			break;
		}
		case QAbstractSocket::ConnectingState:
		{

			break;
		}
		case QAbstractSocket::ConnectedState:
		{

			break;
		}
		case QAbstractSocket::BoundState:
		{

			break;
		}
		case QAbstractSocket::ClosingState:
		{

			break;
		}
		case QAbstractSocket::ListeningState:
		{

			break;
		}
		default:
			break;
		}
	}

} //namespace Core
